<template>
  <vab-dialog v-model:modelValue="dialogVisible" destroy-on-close :title="`${dialogProps.title}用户`" :width="450">
    <el-form
      ref="ruleFormRef"
      :disabled="dialogProps.isView"
      :hide-required-asterisk="dialogProps.isView"
      label-suffix=" :"
      label-width="100px"
      :model="dialogProps.row"
      :rules="env.VITE_RELEASE_NAME === 'fendi' ? rules1 : rules2"
    >
      <el-form-item label="账号" prop="userName">
        <el-input v-model="dialogProps.row!.userName" disabled placeholder="请输入" />
      </el-form-item>
      <el-form-item label="账号类型" prop="userType">
        <el-select v-model="dialogProps.row!.userType" class="w100" disabled>
          <el-option v-for="item in accountType" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="昵称" prop="nickName">
        <el-input v-model="dialogProps.row!.nickName" clearable placeholder="请输入" />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-radio-group v-model="dialogProps.row!.sex">
          <el-radio v-for="item in genderType" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="dialogProps.row!.phone" clearable placeholder="请输入" />
      </el-form-item>
      <el-form-item label="初始密码" prop="defaultPassWord">
        <el-input v-model="dialogProps.row!.defaultPassWord" clearable placeholder="请输入" />
      </el-form-item>
      <el-form-item v-if="dialogProps.row!.registerFlag !== 0" label="前台角色" prop="roles">
        <el-radio-group v-model="dialogProps.row!.posRoleId">
          <el-radio v-for="item in frontRole" :key="item.id" :label="item.name" :value="item.id" />
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="dialogProps.row!.registerFlag !== 0" label="后台角色" prop="roles">
        <el-checkbox-group v-model="dialogProps.row!.roles">
          <el-checkbox v-for="role in RoleList" :key="role.id" :label="role.id">{{ role.roleName }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button v-show="!dialogProps.isView" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </vab-dialog>
</template>

<script setup lang="ts" name="UserMangerDialog">
import { ElMessage, FormInstance } from 'element-plus'
import { reactive, ref } from 'vue'
import { StoreManagement } from '~/src/api/interface/storeManagement'
import { User } from '~/src/api/interface/user'
import { getDepartmentAPI } from '~/src/api/storeManagement'
import { getRoleBackAPI, getRoleFrontAPI } from '~/src/api/user'
import { accountType, genderType } from '~/src/utils/serviceDict'

const env = ref(import.meta.env)
// 密码校验
const validatePass = (rule: any, value: any, callback: any) => {
  const finalCheckPwd =
    /^(?:(?=.*[a-z])(?=.*[A-Z])(?=.*\d)|(?=.*[a-z])(?=.*[A-Z])(?=.*[\W_])|(?=.*[a-z])(?=.*\d)(?=.*[\W_])|(?=.*[A-Z])(?=.*\d)(?=.*[\W_])|(?=.*[A-Z])(?=.*[a-z])(?=.*[\W_])|(?=.*[A-Z])(?=.*[a-z])(?=.*\d)).{8,}$|^$/

  // 校验密码
  const checkPwd: boolean = finalCheckPwd.test(dialogProps.value.row!.defaultPassWord as string)

  if (!checkPwd) {
    callback(new Error('密码必须不少于8位, 包含大小写、字母、字符至少三种'))
  } else {
    callback()
    // 注意，这个空的callback非常重要，没有它作为结束，整个校验会出问题
  }
}

const rules1 = reactive({
  // userName: [{ required: true, message: "请输入账号" }],
  userType: [{ required: true, message: '请选择账号类型' }],
  nickName: [{ required: true, message: '请输入昵称' }],
  sex: [{ required: true, message: '请选择性别' }],
  phone: [{ required: true, message: '请输入手机号' }],
  defaultPassWord: [{ required: true, trigger: 'blur', validator: validatePass }],
})

const rules2 = reactive({
  // userName: [{ required: true, message: "请输入账号" }],
  userType: [{ required: true, message: '请选择账号类型' }],
  nickName: [{ required: true, message: '请输入昵称' }],
  sex: [{ required: true, message: '请选择性别' }],
  phone: [{ required: true, message: '请输入手机号' }],
  defaultPassWord: [{ required: true, trigger: 'blur', message: '请输入' }],
})
const RoleList = ref<User.RoleBack[]>([])

interface DialogProps {
  title: string
  isView: boolean
  row: Partial<User.UserManger>
  api?: (params: any) => Promise<any>
  getTableList?: () => void
}

const dialogVisible = ref(false)
const dialogProps = ref<DialogProps>({
  isView: false,
  title: '',
  row: {},
})

const department = ref<StoreManagement.DepartmentList[]>([])
const frontRole = ref<User.RoleFront[]>([])

// 接收父组件传过来的参数
const acceptParams = async (params: DialogProps) => {
  dialogProps.value = params
  if (dialogProps.value.title === '新增') {
    dialogProps.value.row!.userType = 1
    dialogProps.value.row!.defaultPassWord = ''
    dialogProps.value.row!.sex = 1
  }
  await Promise.all([getDepartment(), getRoleBack(), getRoleFront()])
  dialogVisible.value = true
}

const getDepartment = () => {
  getDepartmentAPI({ pageNum: 1, pageSize: 9999 }).then((res) => {
    department.value = res.data.list
  })
}
const getRoleBack = () => {
  getRoleBackAPI({ pageNum: 1, pageSize: 9999 }).then((val) => {
    RoleList.value = val.data.list
  })
}
const getRoleFront = async () => {
  const res = await getRoleFrontAPI({ pageNum: 1, pageSize: 20 })
  frontRole.value = res.data.list
  if (!dialogProps.value.row.id && res.data.list.length > 0) dialogProps.value.row.posRoleId = frontRole.value[0].id
}

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>()
const handleSubmit = () => {
  ruleFormRef.value!.validate(async (valid) => {
    if (!valid) return
    try {
      await dialogProps.value.api!(dialogProps.value.row)
      ElMessage.success({ message: `${dialogProps.value.title}用户成功！` })
      dialogProps.value.getTableList!()
      dialogVisible.value = false
    } catch (error) {
      console.log(error)
    }
  })
}

defineExpose({
  acceptParams,
})
</script>
